//清理文本
function addBrToText(text) {
  const pattern = /([，。！？\s])/g;
  return text.replace(pattern, '$1<br>');
}
const urlParams = new URLSearchParams(window.location.search);
const poem_id = urlParams.get('poem_id');
const kh = urlParams.get('kh');


document.querySelector('#kh66').addEventListener('click', function () {
  if (kh) {
    window.location.href = "./../index/index.html";
  } else {
    window.history.back();
  }
})

//渲染评论区
async function render() {
  if (!poem_id) {
    console.error('未获取到 poem_id 参数');
    return;
  }
  const user_id = localStorage.getItem('user_id');
  const res1 = await axios({
    url: '/getPoemss',
    params: { poem_id, user_id },
  });

  console.log(res1.msg);

  const plq = document.querySelector('#plq');
  if (res1.code === 0) {
    const item = res1.msg[0];
    console.log(item);
    plq.innerHTML = `
        <div class="text-center mb-6">
          <h2 class="text-2xl font-medium mb-2">${item.title}</h2>
          <p class="text-gray-600">${item.author}</p>
        </div>
        <div class="text-lg leading-loose text-center mb-6" id="qwer">
          ${addBrToText(item.content)}
        </div>
        <div class="flex justify-center gap-4">
          <button class="dz btn1 text-gray-400 hover:text-primary">
          <i class="dz iconfont icon-aixin ${item.is_liked == 1 ? 'red' : ""}"></i>
        <span class="dz ml-1">${item.likes_count}</span>
      </button>
        </div>
      `;

    const btn1 = plq.querySelector(".btn1");
    btn1.addEventListener('click', async function () {
      const res3 = await axios({
        url: '/toggleLike',
        method: 'POST',
        data: { poem_id, user_id }
      });
      if (res3.code === 0) {
        render()
      }
    });
  }
}
render()


function find(x, obj) {
  return obj.map(item => {
    if (item.parent_comment_id == x) {
      return ` <div class="flex gap-4 repl" style="margin-top: 20px;margin-left: 70px;">
      <img src="http://127.0.0.1:3000${item.avatar_url}" class="w-12 h-12 rounded-full object-cover">
      <div class="flex-1">
        <div class="flex items-center justify-between mb-2">
          <div>
            <h4 class="font-medium">${item.nickname}</h4>
            <p class="text-sm text-gray-500">${item.created_at}</p>
          </div>
        </div>
        <p class="text-gray-700 mb-4">
          ${item.content}
        </p>
      </div> 
    </div>
    ${find(item.comment_id, obj)}` // 递归查找子评论
    }
  }).join("")
}

// 渲染评论
async function renderpl() {
  const urlParams = new URLSearchParams(window.location.search);
  const poem_id = urlParams.get('poem_id');
  if (!poem_id) {
    console.error('未获取到 poem_id 参数');
    return;
  }
  const res2 = await axios({
    url: '/getPoempl',
    params: { poem_id },
  })
  console.log(res2.msg);
  const pl = document.querySelector('#pl')
  if (res2.code == 0) {
    console.log(res2.msg.comments);
    pl.innerHTML = `<div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-medium">全部评论 (${res2.msg.commentCount})</h3>
            <div class="flex gap-4">
              <button
                class="flex items-center gap-2 text-gray-500 hover:text-primary transition-colors !rounded-button">
                <i class="fas fa-sort-amount-down"></i>
                <span>最新</span>
              </button>
              <button
                class="flex items-center gap-2 text-primary hover:text-secondary transition-colors !rounded-button">
                <i class="fas fa-fire"></i>
                <span>最热</span>
              </button>
            </div>
          </div>`
    
    // 主要修改点：只处理父级评论（parent_comment_id为null的项）
    const str = res2.msg.comments
      .filter(item => item.parent_comment_id === null) // 只筛选父级评论
      .map(item => {
        return `
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex gap-4">
            <img src="http://127.0.0.1:3000${item.avatar_url}" class="w-12 h-12 rounded-full object-cover">
            <div class="flex-1">
              <div class="flex items-center justify-between mb-2">
                <div>
                  <h4 class="font-medium">${item.nickname}</h4>
                  <p class="text-sm text-gray-500">${item.created_at}</p>
                </div>
              </div>
              <p class="text-gray-700 mb-4">
                ${item.content}
              </p>
              <div class="flex gap-4 allkh">
                <button class="text-gray-500 hover:text-primary transition-colors !rounded-button"  data-id="${item.comment_id}">
                  <i class="far fa-comment"></i>
                  <span class="ml-1">回复</span>
                </button>
              </div>
            </div> 
          </div>
          ${find(item.comment_id, res2.msg.comments)}
        </div>`
      }).join("")
    
    pl.innerHTML += str
  }

  const hfan = document.querySelectorAll('.allkh button')
  const bjzp = document.querySelector('.bjzp')
  const plk = document.querySelector('.plk')
  hfan.forEach(item => {
    item.addEventListener('click', function () {
      document.querySelector("#xgzp").dataset.id = item.dataset.id
      plk.style.display = "none";
      bjzp.style.display = "block";
      document.body.style.overflow = 'hidden';
    })
  })

  document.querySelector(".bjzp i").addEventListener("click", () => {
    bjzp.style.display = "none";
    plk.style.display = "block";
    document.body.style.overflow = 'auto';
  })
}

renderpl()

//回复评论
const replk= document.querySelector('#replk')
document.querySelector("#xgzp").addEventListener("click", async function (e) {
  e.preventDefault()
  const urlParams = new URLSearchParams(window.location.search);
  const poem_id = urlParams.get('poem_id');
  if (!poem_id) {
    console.error('未获取到 poem_id 参数');
    return;
  }
  const user_id = localStorage.getItem('user_id');
  if (!user_id) {
    console.error('未获取到 user_id');
    return;
  }
  
  const res4 = await axios({
    url: '/readdComment',
    method: 'post',
    data: {
      poem_id,
      user_id,
      content: replk.value,
      parent_comment_id: this.dataset.id
    }
  })
  console.log(res4.msg);
  if (res4.code == 0) {
    alert('评论成功')
    window.location.reload()
  }
})

//提交评论
const tjpl = document.querySelector('#tjpl')
const pltext = document.querySelector('#pltext')
tjpl.addEventListener('click', async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const poem_id = urlParams.get('poem_id');
  if (!poem_id) {
    console.error('未获取到 poem_id 参数');
    return;
  }
  const user_id = localStorage.getItem('user_id');
  if (!user_id) {
    console.error('未获取到 user_id');
    return;
  }

  const res3 = await axios({
    url: '/addComment',
    method: 'post',
    data: {
      poem_id,
      user_id,
      content: pltext.value
    }
  })
  console.log(res3.msg);
  if (res3.code == 0) {
    alert('评论成功')
    window.location.reload()
  }
})
